package user.view;

import static org.math.array.DoubleArray.increment;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;

import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.text.JTextComponent;

import model.doe.FresnelAnnular;
import model.util.FourerExecutor;
import model.util.FourerExecutor.DoeType;

import system.activity.MainListener;
import system.elements.ControlTextField;
import system.util.PlotBuilder;

public class FresnelAnnularImpl extends Controls
{

	private javax.swing.JLabel angelLabel;
	private ControlTextField angelText;
	private javax.swing.JButton cancelButton;
	private javax.swing.JLabel descrLabel;
	private ControlTextField descrText;
	private javax.swing.JLabel focusLabel;
	private ControlTextField focusText;
	private javax.swing.JButton okButton;
	private javax.swing.JLabel radLabel;
	private ControlTextField radText;
	private javax.swing.JLabel wlLabel;
	private ControlTextField wlText;

	private javax.swing.JCheckBox phase;
	private javax.swing.JCheckBox signPhase;
	private javax.swing.JCheckBox fourer;

	public FresnelAnnularImpl(final MainListener listener)
	{
		this.listener = listener;
		this.setLayout(new java.awt.BorderLayout());

		init();
	}

	public FresnelAnnularImpl(final MainListener listener, ArrayList<String> params)
	{
		this.listener = listener;
		this.setLayout(new java.awt.BorderLayout());
		initFromHistory(params);
	}
	
	@Override
	protected LinkedList<JTextComponent> elementsQueue()
	{
		LinkedList<JTextComponent> result = new LinkedList<JTextComponent>();
		result.add(radText);
		result.add(angelText);
		result.add(focusText);
		result.add(wlText);
		result.add(descrText);
		return result;
	}
	
	@Override
	protected void init()
	{
		radLabel = new javax.swing.JLabel();
		radText = new ControlTextField();
		angelLabel = new javax.swing.JLabel();
		angelText = new ControlTextField();
		focusText = new ControlTextField();
		wlText = new ControlTextField();
		descrText = new ControlTextField();
		focusLabel = new javax.swing.JLabel();
		wlLabel = new javax.swing.JLabel();
		descrLabel = new javax.swing.JLabel();
		okButton = new javax.swing.JButton();
		cancelButton = new javax.swing.JButton();
		
		phase = new javax.swing.JCheckBox();
		signPhase = new javax.swing.JCheckBox();
		fourer = new javax.swing.JCheckBox();
		phase.setText("Расчет фазы");
		signPhase.setText("Расчет знака фазы");
		fourer.setText("Выполнить преобразование Фурье");

		fourer.setEnabled(false);
		phase.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				checkFourerAvailable();
			}

		});

		setName("Form"); // NOI18N

		radLabel.setText("Радиус апертуры"); // NOI18N
		radLabel.setName("radLabel"); // NOI18N

		radText.setText("6.4"); // NOI18N
		radText.setName("radText"); // NOI18N

		angelLabel.setText("Угол"); // NOI18N
		angelLabel.setName("angelLabel"); // NOI18N

		angelText.setText("0"); // NOI18N
		angelText.setName("angelText"); // NOI18N

		focusText.setText("100.0"); // NOI18N
		focusText.setName("focusText"); // NOI18N

		wlText.setText("10.6"); // NOI18N
		wlText.setName("wlText"); // NOI18N

		descrText.setText("0.025"); // NOI18N
		descrText.setName("descrText"); // NOI18N

		focusLabel.setText("Фокальное расстнояние"); // NOI18N
		focusLabel.setName("focusLabel"); // NOI18N

		wlLabel.setText("Длина волны (мкм)"); // NOI18N
		wlLabel.setName("wlLabel"); // NOI18N

		descrLabel.setText("Шаг дескретизации"); // NOI18N
		descrLabel.setName("descrLabel"); // NOI18N

		okButton.setText("Рассчитать"); // NOI18N
		okButton.setName("okButton"); // NOI18N

		cancelButton.setText("Закрыть"); // NOI18N
		cancelButton.setName("cancelButton"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(signPhase)
                    .addComponent(phase)
                    .addComponent(fourer)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(okButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(descrLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(radLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)
                            .addComponent(angelLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(focusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(wlLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(descrText, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(wlText, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(focusText, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(angelText, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(radText, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radLabel)
                    .addComponent(radText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(angelLabel)
                    .addComponent(angelText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(focusLabel)
                    .addComponent(focusText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wlLabel)
                    .addComponent(wlText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(descrLabel)
                    .addComponent(descrText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(phase)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(signPhase)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fourer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 137, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );
		okButton.addMouseListener(new java.awt.event.MouseAdapter()
		{
			public void mouseClicked(java.awt.event.MouseEvent evt)
			{
				try {
					okButton.setEnabled(false);
					final FresnelAnnular fresnelAnnular = new FresnelAnnular(Double.parseDouble(radText.getText()), Double.parseDouble(angelText.getText()),
							Double.parseDouble(focusText.getText()), Double.parseDouble(wlText.getText()), Double.parseDouble(descrText.getText()));
					listener.clearImagePanel();
					listener.setLoadStatus();
					java.awt.event.ActionListener actionListener = new java.awt.event.ActionListener()
					{
						public void actionPerformed(java.awt.event.ActionEvent actionEvent)
						{
							try {
								if (phase.isSelected()) {
									listener.addImagePanel(fresnelAnnular.getPhaseTo2PiMImage(), "Распределение фазы");
								}
								if (signPhase.isSelected()) {
									listener.addImagePanel(fresnelAnnular.getSignPhaseImage(), "Распределение знака фазы");
								}
								if (phase.isSelected() && fourer.isSelected()) {
									FourerExecutor fourer = new FourerExecutor();
									ArrayList<BufferedImage> fourerImages = fourer.fft(fresnelAnnular, DoeType.PHASE);
									listener.addImagePanel(fourerImages.get(0),"Распредление амплитуды после преобразования Фурье");
									
									double[][] z = fourer.getResultAmpl();
									double[] x = increment(0d, 1d, z[0].length);
									double[] y = increment(0d, 1d, z.length);
									String plotDescription = "Распределение амплитуды после преобразования Фурье - график";
									listener.addFastPlotPanel(PlotBuilder.buildFast3DPlot(x, y, z, plotDescription), "Распределение амплитуды после преобразования Фурье - график");
									
									
									listener.addImagePanel(fourerImages.get(1),"Распредление фазы после преобразования Фурье");
									onResize();
									listener.needRepaint();
								}
								onResize();
								listener.needRepaint();
								listener.removeLoadStatus();
								okButton.setEnabled(true);
							} catch (OutOfMemoryError ex) {
								listener.removeLoadStatus();
								okButton.setEnabled(true);
								listener.showErrorMessage("Перепелнение памяти");
							}
							catch(IllegalArgumentException ex)
							{
								listener.removeLoadStatus();
								okButton.setEnabled(true);
								listener.showErrorMessage(ex.getMessage());
							}
						}
					};
					Timer timer = new Timer(500, actionListener);
					timer.setRepeats(false);
					timer.start();
				} catch (NumberFormatException ex) {
					listener.showErrorMessage("Ошибка формата входных данных");
					listener.removeLoadStatus();
					okButton.setEnabled(true);
				}
				catch(IllegalArgumentException ex)
				{
					listener.removeLoadStatus();
					okButton.setEnabled(true);
					listener.showErrorMessage(ex.getMessage());
				}
			}
		});
		cancelButton.addMouseListener(new java.awt.event.MouseAdapter()
		{
			public void mouseClicked(java.awt.event.MouseEvent evt)
			{
				listener.removeLeftPanel();
				onResize();
				listener.needRepaint();
			}
		});
		Border border = BorderFactory.createEtchedBorder(Color.white, new Color(178, 178, 178));
		this.setBorder(border);
		listener.addPanel(this);
		this.show();
	}

	void onResize()
	{
		this.show();
	}

	@Override
	public void setListener(MainListener listener)
	{
		this.listener = listener;
	}

	@Override
	public Collection<String> getControlsValues()
	{
		Date date = new Date();
		Collection<String> result = new ArrayList<String>();
		result.add("                                                                                 " + date.getHours() + ":" + date.getMinutes() + ":"
				+ date.getSeconds() + "   " + date.getDate() + "." + (date.getMonth() + 1) + "." + (date.getYear() + 1900));
		result.add("Линза френеля");
		result.add("Введенные параметры:");
		result.add(radLabel.getText() + " = " + radText.getText());
		result.add(angelLabel.getText() + " = " + angelText.getText());
		result.add(focusLabel.getText() + " = " + focusText.getText());
		result.add(wlLabel.getText() + " = " + wlText.getText());
		result.add(descrLabel.getText() + " = " + descrText.getText());
		result.add("");
		return result;
	}
	@Override
	String getClassName()
	{
		return this.getClass().getCanonicalName();
	}
	private void checkFourerAvailable() {
		fourer.setEnabled(phase.isSelected());
		if(fourer.isEnabled() == false)
		{
			fourer.setSelected(false);
		}
	}
	
	
}
